#!/usr/bin/env ruby -wKU
#encoding: utf-8

require 'action_mailer'

module Mail_VTB
  
  # Use 163 mail since I don't why gmail does not work.
  
  # TODO: move these settings into a separate configuration file, then read from it
  # TODO: use something like mail_queue to send mail in an asynchronized way to reduce workload
  # eg. write info into database, then use another application to send mail
  
  #SENDER = 'valuable_to_buy@163.com'
  #SENDER_PASSWD = 'Qqqqq12345'
  
  SENDER = 'jugu@microstrategy.com'
  SENDER_PASSWD = 'QQqqq12345'
  
  # puts 'in mail'
  
  ActionMailer::Base.smtp_settings = {
    address:              'CORP-EXCL1-WAS' #'smtp.163.com',
    #port:                 25,
    #domain:               '163.com',
    #user_name:            SENDER,
    #password:             SENDER_PASSWD,
    #authentication:       'login',
    #enable_starttls_auto: true
  }
  
  # use ActionMailer without Rails
  ActionMailer::Base.view_paths = File.dirname(__FILE__)
  
  class NotificationMail < ActionMailer::Base
    
    default :from => SENDER
    
    def notification toMail, items
      
      # puts 'plan to send mail'
      
      @items = items
      
      mail(to: toMail, subject: "Valuable To Buy") do |format|
        format.text
        format.html
      end
      
    end
    
  end
  
  if __FILE__ == $0
    toMail = "jugu@microstrategy.com"
    # toMail = SENDER
    
    data = []
    
    require 'backend/crawler/html_parser'
    rtn = Crawler::HtmlParser.crawl
    data << rtn
    # puts rtn
    
    start = Time.now
    mail = NotificationMail.notification toMail, data
    mail.deliver
    elapsed = Time.now - start
    puts "Used #{elapsed} time to send first mail"
    # puts mail
#     
    # start = Time.now
    # mail = NotificationMail.notification toMail, data
    # mail.deliver
    # elapsed = Time.now - start
    # puts "Used #{elapsed} time to send second mail"
    # puts mail
    
    # Net::SMTP.start('CORP-EXCL1-WAS') do |smtp|
      # smtp.sendmail('hello mail', 'bwang@microstrategy.com', 'jugu@microstrategy.com')
      # puts 'sent'
    # end
    
  end
  
end